using ABFramework;
using System;
using System.Collections;
using System.Collections.Generic;
using UIFramework;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using XLua;

/// <summary>
/// 场景加载管理器
/// </summary>
public class LoadSceneManager : MonoBehaviour
{
    #region 实现LoadAssetsManager类的单例
    private static LoadSceneManager _instance;
    private LoadSceneManager() { }
    public static LoadSceneManager Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = GameInit.GameManager.AddComponent<LoadSceneManager>();
            }
            return _instance;
        }
    }
    #endregion

    //加载场景显示面板
    GameObject _LoadScenePanel = null;
    Slider _AssetsLoadSlider = null;
    Slider _SceneLoadSlider = null;
    Text _SceneLoadInfoText = null;
    Text _SceneLoadTipsText = null;

    /// <summary>
    /// 初始化
    /// </summary>
    public void Init()
    {
        //Debug.Log("LoadSceneManager Init!");
    }

    /// <summary>
    /// 异步加载场景，并显示加载界面
    /// </summary>
    /// <param name="scene_name">场景名称</param>
    /// <param name="callback">加载完成的回调</param>
    /// <param name="release_assets">释放上一个场景加载的资源包，不包括公共资源</param>
    /// <param name="moudles">需要加载的模块，可以没有</param>
    public void Load(string scene_name, Action callback, bool release_assets = true, params string[] moudles)
    {
        //释放上一个场景加载的资源
        if (release_assets)
        {
            AssetBundleManager.Instance.UnLoadAllSceneAssetBundles();
        }
        //关闭切换场景需要关闭的UI
        UIManager.Instance.ChangeSceneCloseUI();

        //加载场景和资源包
        StartCoroutine(DoLoad(scene_name, callback, moudles));
    }

    /// <summary>
    /// 执行加载场景
    /// </summary>
    /// <param name="scene_name">场景名字</param>
    /// <param name="callback">回调</param>
    /// <param name="moudles">需要加载的模块资源数组</param>
    /// <returns></returns>
    IEnumerator DoLoad(string scene_name, Action callback, params string[] moudles)
    {
        //加载并显示加载界面
        if (_LoadScenePanel == null)
        {
            Transform parent = GameObject.Find("Canvas/Topest").transform;
            _LoadScenePanel = Instantiate(LoadAssetManager.Instance.LoadPrefab(@"Common\Loading\AsyncLoadScene"), parent);
            _LoadScenePanel.name = _LoadScenePanel.name.Replace("(Clone)", "");
        }
        _LoadScenePanel.transform.SetAsLastSibling();
        _LoadScenePanel.GetComponent<CanvasGroup>().alpha = 1;
        //设置引用以及播放随机小提示
        SetLoadReference();
        StartCoroutine(RandomChangeTips());
        //yield return new WaitForSeconds(1);

        yield return AssetBundleManager.Instance.DoLoadModules(false, ChangeLoadABProgress, moudles);
        yield return new WaitForSeconds(1);

        //加载场景 前提是资源加载完成(等上一个yield reutrun返回则表示资源加载成功)
        AsyncOperation op = AsyncLoadScene(scene_name, LoadSceneMode.Single);

        //op.allowSceneActivation = false;
        //进度显示
        while (!op.isDone)
        {
            _SceneLoadSlider.value = op.progress;
            yield return null;
        }
        yield return new WaitForSeconds(0.2f);

        _SceneLoadSlider.value = 1;

        //隐藏加载面板
        DTAnimManager.Instance.FadeOut(_LoadScenePanel.GetComponent<CanvasGroup>(), () =>
        {
            _LoadScenePanel.SetActive(false);
        }, DTAnimSpeed.Quick);

        //op.allowSceneActivation = true;
        //执行回调
        callback?.Invoke();
    }

    /// <summary>
    /// 异步加载场景
    /// </summary>
    /// <param name="scene_name"></param>
    /// <param name="loadSceneMode"></param>
    /// <returns></returns>
    private AsyncOperation AsyncLoadScene(string scene_name, LoadSceneMode loadSceneMode)
    {
#if UNITY_EDITOR
        if (!GameInit.Instance._EnabledHotUpdate)
        {
            /*注意，路径不要写错了,不然会给你创建一个啥也没有的空场景*/
            scene_name = "Assets/Module/Editor/" + scene_name + ".unity";
            //Debug.Log(scene_name);
            return UnityEditor.SceneManagement.EditorSceneManager.LoadSceneAsyncInPlayMode(scene_name, new LoadSceneParameters(loadSceneMode));
        }
        else
        {
            scene_name = scene_name.Split('/')[scene_name.Split('/').Length - 1];
            return SceneManager.LoadSceneAsync(scene_name, loadSceneMode);
        }
#else
        scene_name = scene_name.Split('/')[scene_name.Split('/').Length - 1];
        return SceneManager.LoadSceneAsync(scene_name, loadSceneMode);
#endif
    }

    /// <summary>
    /// 设置加载界面的引用
    /// </summary>
    /// <param name="go"></param>
    void SetLoadReference()
    {
        UINameTable uname = _LoadScenePanel.GetComponent<UINameTable>();

        _AssetsLoadSlider = uname.GORefrence["LoadAssetsBar"].GetComponent<Slider>();
        _SceneLoadSlider = uname.GORefrence["LoadSceneBar"].GetComponent<Slider>();
        _SceneLoadInfoText = uname.GORefrence["LoadInfo"].GetComponent<Text>();
        _SceneLoadTipsText = uname.GORefrence["Tips"].GetComponent<Text>();
    }
    /// <summary>
    /// 显示加载资源的进度
    /// </summary>
    /// <param name="cur"></param>
    /// <param name="total"></param>
    void ChangeLoadABProgress(int cur, int total)
    {
        _AssetsLoadSlider.value = cur * 1.0f / total;
        _SceneLoadTipsText.text = "场景资源加载中...";
    }

    /// <summary>
    /// 加载界面的随机小提示
    /// </summary>
    /// <returns></returns>
    IEnumerator RandomChangeTips()
    {
        while (_LoadScenePanel != null)
        {
            yield return new WaitForSeconds(2);
            //TODO
            _SceneLoadTipsText.text = "???";
        }
    }

}
